#qpy:console
import androidhelper as _android
import time
import json


def main():                     # {{{1
    global android
    android = _android.Android()

    h = None
    for k, v in android.usbserialGetDeviceList().result.items():
        print(k, v)
        #if '"0409","FFFD"' in v:
        # v is '["device-name","VID","PID","hashCode"]'
        h = json.loads(v)[-1]
        print("device was found, try to connect =>", h)
    if h is None:
        print("device was not found")
        return

    ret = android.usbserialConnect(h, "trg78k")
    if not "OK" in ret.result:
        print("can't connect to device: ", ret.result)
        return
    # ret is '["OK","UUID"]'
    print(ret.result)
    uuid = json.loads(ret.result)[-1]
    print("connected with ", h, uuid)

    # wait until the permission be allowed by user.
    n = 0
    readreadyresult = android.usbserialReadReady(uuid).result
    #print('read ready:',readreadyresult)
    while not readreadyresult and n<10:
        n += 1
        readreadyresult = android.usbserialReadReady(uuid).result
        print('read ready:',readreadyresult)
        print("waiting for connect....", n)
        time.sleep(1)

    # now get data from USB-Serial.
    n = 1
    buf = android.usbserialWrite("ON", uuid)
    while True:
        time.sleep(5)

        buf = android.usbserialRead(uuid)
        print("Received: ", buf)

        if n >= 0:
            n += 10
            if n > 255:
                n = -1
        elif n < 0:
            n -= 10
            if n < -255:
                n = 0

        if n < 0:
            send = "B%03dB%03d" % (n, n)
        else:
            send = "F%03dF%03d" % (n, n)

        #send = "F000B%03d" % n
        #send = "F000B%03d" % n
        buf = android.usbserialWrite(send, uuid)


if __name__ == "__main__":      # {{{1
    main()
